/**
 * Created by ruiyuan on 15-8-11.
 */

var Users = mongoose.model('user');
var userAuthentication = mongoose.model('user_authentications');
var roleAction = mongoose.model('masterData_roleActions');
var async = require('async');
var toolUtil = require('../common/utils/toolUtil');
var mysqlUtil = require('../common/utils/mysqlUtil');
var http = require('http');
var querystring = require('querystring');
var md5 = require('MD5');
var moment = require('moment');
var communityCity = mongoose.model('community_city');
var community = mongoose.model('community');
var geolib = require('geolib');
var userController = require('../controllers/user-controller');
var userService = require('./userService');
var userInvitation = mongoose.model('user_invitation');
var invitationShare = mongoose.model('user_invitation_share');
var deviceCodeBind = mongoose.model('relation_deviceCodeBind');
var pinyin = require("pinyin");
var locationV = mongoose.model('community_location_v');
var Regions = mongoose.model('masterData_Regions');
var UserTask = mongoose.model('user_task');
var UserRoleApply = mongoose.model('user_role_apply');
var UserInvitationRecord = mongoose.model('user_invitation_share');
var Group = mongoose.model('group_family');
var groupService = require('./groupService');
var splashScreen = mongoose.model('system_splashScreen');
var Question = mongoose.model('question');
var mutualAidService = require('./mutualAidService');
/*  宝宝树66小区二次改造    add   chenf  20170714   start   */
var taskService = require('../services/taskService');
var signInfo = mongoose.model('sign_info');
var ambassadorCommunity = mongoose.model('ambassador_community');
/*  宝宝树66小区二次改造    add   chenf  20170714   end   */
/*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170821   start   */
var Geetest = require('gt3-sdk');
/*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170821   end   */
/**
 * 获取手机号状态
 * @param mobilePhone  电话号码
 * @param callback
 */
exports.getMobilePhoneStatusService = function (mobilePhone, callback) {
    Users.findOne({mobilePhone: mobilePhone}, function (err, result) {
        callback(err, {isRegister: result != null})
    })
};

/**
 * 获取短信验证码
 * @param mobilePhone   电话号码
 * @param type          1,注册;2,忘记密码;3,绑定;4,修改密码
 * @param callback
 */
exports.getSmsVerificationCodeService = function (mobilePhone, type, callback) {

    userService.isBabyTreeUser(mobilePhone, function (err, tempCount) {
        if (err) {
            logger.error("Failed to isBabyTreeUser - " + err.message);
            callback(err, null);
        } else {
            if(tempCount > 0) {
                // 是宝宝树用户(不可以注册:1,可以修改密码:2和忘记密码:4)
                if(type == '2' || type == '4') {
                    var key = 'ver:code:' + mobilePhone + ':' + type;
                    redisClient.get(key, function (err, value) {
                        logger.debug(value);
                        if (value == null) {
                            callback(null, toolUtil.generateVerificationCode(mobilePhone, key))
                        } else {
                            callback(null, value);
                        }
                    });
                } else {
                    logger.debug("已经注册用户再次注册..." + mobilePhone);
                    callback({status:0,message:"非法操作"}, null);
                }
            } else {
                // 不是宝宝树用户(可以注册:1,不可以修改密码:2和忘记密码:4)
                if(type == '1') {
                    var key = 'ver:code:' + mobilePhone + ':' + type;
                    redisClient.get(key, function (err, value) {
                        logger.debug(value);
                        if (value == null) {
                            callback(null, toolUtil.generateVerificationCode(mobilePhone, key))
                        } else {
                            callback(null, value);
                        }
                    });
                } else {
                    logger.debug("非宝宝树用户不可以修改密码或忘记密码..." + mobilePhone);
                    callback({status:0,message:"非法操作"}, null);
                }
            }
        }
    });

    // var key = 'ver:code:' + mobilePhone + ':' + type;
    // redisClient.get(key, function (err, value) {
    //     logger.debug(value);
    //     if (value == null) {
    //         callback(null, toolUtil.generateVerificationCode(mobilePhone, key))
    //     } else {
    //         callback(null, value);
    //     }
    // });

};


/**
 * 获取语音验证码
 * @param mobilePhone   电话号码
 * @param type          1,注册;2,忘记密码;3,绑定
 * @param callback
 */
exports.getVoiceVerificationCodeService = function (mobilePhone, type, callback) {

    exports.getSmsVerificationCodeService(mobilePhone, type, function (err, code) {
        if (err) {
            callback(err)
        } else {
            var post_data = querystring.stringify({
                'apikey': 'c938679e6bab4e1504332217839228d8',
                'mobile': mobilePhone,
                'code': code,
                'display_num': voicePhone
            });

            var post_options = {
                host: 'voice.yunpian.com',
                path: '/v1/voice/send.json',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
                    'Accept': "application/json;charset=utf-8",
                    'Content-Length': post_data.length
                }
            };

            var post_req = http.request(post_options, function (res) {
                res.setEncoding('utf8');
                res.on('data', function (chunk) {
                    var data = JSON.parse(chunk);
                    if (data.code == 0) {
                        callback(null)
                    } else {
                        logger.error('Failed to getVoiceVerificationCodeService --- ' + data.msg);
                        callback(ErrorMessage.VOICE_ERROR)
                    }
                });
            });

            post_req.write(post_data);
            post_req.end();
        }
    })
};


/**
 * 校验验证码
 * @param mobilePhone   手机号
 * @param type          1,注册;2,忘记密码;3,绑定
 * @param code          验证码
 * @param callback
 */
exports.checkVerificationCodeService = function (mobilePhone, type, code, callback) {
    var key = 'ver:code:' + mobilePhone + ':' + type;

    /*  宝宝树66小区四次改造 任意手机号注册安全问题   mod   guo.xiaomin  20171024   start   */
    // 验证码错误次数
    var errorKey = key + ":errorCount";
    redisClient.get(errorKey, function(err, getReply) {
        if(getReply != null && getReply >= 9) {
            logger.debug("验证码错误次数太多，锁定1小时!..." + errorKey);
            callback({status: 0, message: '验证码错误次数太多，锁定1小时!'});
        } else {
            redisClient.get(key, function (err, value) {
                if (value != null && value == code) {
                    callback();
                } else {
                    redisClient.incr(errorKey, function(err, reply) {
                        redisClient.expire(errorKey, 3600); // 1小时
                        logger.debug("验证码错误..." + errorKey);
                        callback({status: 0, message: '验证码错误'});
                    });
                }
            });
        }
    });
    /*  宝宝树66小区四次改造 任意手机号注册安全问题   mod   guo.xiaomin  20171024   end   */
     // redisClient.get(key, function (err, value) {
     //     if (value != null && value == code) {
     //         callback()
     //     } else {
     //         callback({status: 0, message: '验证码错误'})
     //     }
     // });
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170902   start   */
    // callback();
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170902   end   */
};

/*  宝宝树66小区二次改造    add   llh  20170717   start   */
/**
 * 注册时取得宝宝树信息
 * @param mobilePhone   手机号
 * @param callback
 */
exports.getBabyTreeRegisterUserInfoService = function (mobilePhone, callback) {
    /*  宝宝树66小区二次改造    mod   dayu  20170723   start   */
    restClient.get('http://sixsix.babytree.com/sixsix/user/login?phone_number=' + mobilePhone , function (data, response) {
        /*  宝宝树66小区二次改造    mod   dayu  20170723   end   */
        if (response.statusCode == 200) {
            try {
                callback(null, data);
            } catch (e) {
                callback(e, null);
            }
        } else {
            var err = {
                "message": 'statusCode:' + response.statusCode
            };
            callback(err, null);
        }
    }).on('error', function (err) {
        logger.error('get weather went wrong on the request' + err.message);
    });
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170906   start   */
exports.checkNickNameCanUse = function (nickName, callback) {
    var nickNm = encodeURIComponent(nickName);
    var url = "http://" + ssoUrl + "/sso/sso.ajax.php?action=has_nickname&nickname=" + nickNm;
    restClient.get(url, function (data, response) {
        if (response.statusCode == 200) {
            try{
                var objData = {};
                objData = JSON.parse(data);
                if (objData.status == 1) {
                    // 昵称正常
                    callback(null, true);
                } else {
                    // 宝宝树已经注册了，数据异常
                    exports.getErrorMsg(objData.error, function(msg){
                        logger.error(objData+"," + msg);
                        callback(null, false);
                    });
                }
            } catch(e) {
                logger.error(e.message);
                callback(null, false);
            }
        } else {
            logger.error(e.message);
            callback(null, false);
        }
    }).on('error', function (err) {
        logger.error('get weather went wrong on the request' + err.message);
        callback(null, false);
    });
};

/*  宝宝树66小区三次改造    mod   guo.xiaomin  20171017   start   */
// 检查本地是否有当前昵称
exports.checkLocalNickNameCanUse = function (nickName, callback) {
    Users.count({
        nickName: nickName
    }).exec(function (err, count) {
        if (err) {
            callback(null, false);
        } else {
            if (count > 0) {
                callback(null, true);
            } else {
                callback(null, false);
            }
        }
    });
};
/*  宝宝树66小区三次改造    mod   guo.xiaomin  20171017   end   */
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170906   end   */

/**
 * 重置密码
 * @param mobilePhone
 * @param type
 * @param code
 * @param password
 * @param callback
 */
exports.resetPasswordService = function (mobilePhone, type, code, password, clientIp, callback) { // 新
// exports.resetPasswordService = function (mobilePhone, type, code, password, callback) { // 旧
    async.series([
        function (callbackInner) {
            exports.checkVerificationCodeService(mobilePhone, type, code, callbackInner);
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170902   start   */
            // callbackInner();
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170902   end   */
        },
        function (callbackInner) {
            /*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170824   start   */
            // Users.update({mobilePhone: mobilePhone}, {userPassword: md5(password)}, callbackInner);
            Users.find({mobilePhone: mobilePhone}, function (err, user) {
                if (err) {
                    callbackInner(err);
                } else if (user == null || user.length == 0) {
                    callbackInner({status:0, message : "为了您账号安全，重置密码请去宝宝树孕育操作"});
                } else if (user.length > 1) {
                    callbackInner({status:0, message : "手机异常"});
                } else {
                    if (user[0].encUserId == null || user[0].encUserId == '') {
                        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170926   start   */
                        // 更新本地密码+去掉隐形注册
                        Users.update({mobilePhone: mobilePhone}, {userPassword: md5(password)}, function(err, updLocResult) {
                            logger.debug(updLocResult);
                            if (err) {
                                // 修正本地失败
                                callbackInner(err);
                            } else {
                                // 修正本地成功,修正宝宝树密码
                                callbackInner();
                            }
                        });
                        // // 隐形注册
                        // var nickName = user[0].nickName;
                        // // 先检查昵称是否存在
                        // exports.checkNickNameCanUse(nickName, function(err, flag) {
                        //     if(!flag) {
                        //         nickName = nickName + toolUtil.getRandomNumberByNum(6);
                        //     }
                        //     var input = {
                        //         nickName : nickName,
                        //         mobilePhone : mobilePhone,
                        //         userPassword : password,
                        //         olduser : 0
                        //     };
                        //
                        //     exports.registerSsoService(input, function(err, registerResult) {
                        //         if (err) {
                        //             // 注册失败
                        //             logger.error('registerSsoService:::');
                        //             logger.error(err);
                        //             // /*  宝宝树66小区二次改造    add  修改本地密码 luolh  20170914   start   */
                        //             // if ("手机号已经注册" == err.message) {
                        //             //      // 修改密码66密码可
                        //             //     Users.update({mobilePhone: mobilePhone}, {userPassword: md5(password)}, callbackInner);
                        //             // } else {
                        //             //     callbackInner({status:0, message:"网络异常"});
                        //             // }
                        //             // /*  宝宝树66小区二次改造    add  修改本地密码 luolh  20170914   end   */
                        //             callbackInner({status: 0, message: "此用户数据异常,请去宝宝树APP修改此密码!"});
                        //         } else {
                        //             // 修正enc_user_id
                        //             logger.debug(registerResult.enc_user_id + ">注册后返回的数据>" + registerResult);
                        //             Users.update({_id: user._id}, {
                        //                 encUserId: registerResult.enc_user_id,
                        //                 userPassword: ''
                        //             }, function (err, result) {
                        //                 logger.debug(result);
                        //                 if (err) {
                        //                     // 修正本地失败
                        //                     logger.error("修改本地密码失败" + err);
                        //                     callbackInner(err);
                        //                 } else {
                        //                     // 隐形注册成功
                        //                     logger.debug('重置密码的时候隐形注册成功...');
                        //                     callbackInner();
                        //                 }
                        //             });
                        //         }
                        //     });
                        // });
                        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170926   end   */
                    } else {
                        exports.updateSsoPassword(user[0].encUserId, password, clientIp, function(err, updRemoteResult){ // 新
                        // exports.updateSsoPassword(user[0].encUserId, password, function(err, updRemoteResult){ // 旧
                            if (err) {
                                // 修正失败
                                callbackInner(err);
                            } else {
                                // 修正成功,修正66密码
                                Users.update({mobilePhone: mobilePhone}, {userPassword: ''}, function(err, updLocResult) {
                                    logger.debug(updLocResult);
                                    if (err) {
                                        // 修正本地失败
                                        callbackInner(err);
                                    } else {
                                        // 修正本地成功,修正宝宝树密码
                                        callbackInner();
                                    }
                                });
                            }
                        });
                    }
                }
            });
            /*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170824   end   */
        }
    ], callback)
};

/**
 * 注册（设置密码和昵称）（或绑定未注册手机号）
 * @param input
 * @param callback
 */
exports.signUpService = function (input, clientIp, callback) { // 新
// exports.signUpService = function (input, callback) { // 旧

    if (input.nickName == null || input.nickName.trim() == '') {
        callback({status: 0, message: '请输入昵称'})
    } else {
        /*  宝宝树66小区二次改造    add   llh  20170717   start   */
            async.series([
                function (callbackInner) {
                    var err = {status: 0, message: '网络异常,请重试'};
                    /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   start */
                    // if (input.encUserId == null || input.encUserId == '') {
                    //     // 如果用户为空
                    //     var nickNm = encodeURIComponent(input.nickName);
                    //     /*  宝宝树66小区二次改造    mod   dayu  20170723   start   */
                    //     //restClient.get('http://test26.babytree-dev.com/sexsex/user/register?phone_number=' + input.mobilePhone + '&nickname=' + nickNm, function (data, response) {
                    //     restClient.get('http://sixsix.babytree.com/sixsix/user/register?phone_number=' + input.mobilePhone + '&nickname=' + nickNm, function (data, response) {
                    //         /*  宝宝树66小区二次改造    mod   dayu  20170723   end   */
                    //         if (response.statusCode == 200) {
                    //             try {
                    //                 var objData = {};
                    //                 objData = JSON.parse(data);
                    //                 var status = objData.status;
                    //                 if ("success" == status) {
                    //                     input.encUserId = objData.data.enc_user_id;
                    //                     callbackInner();
                    //                 } else {
                    //                     // 宝宝树已经注册了，数据异常
                    //                     err = {status: 0, message: objData.message};
                    //                     callbackInner(err);
                    //                 }
                    //             } catch (e) {
                    //                 logger.error(e.message);
                    //                 callbackInner(err);
                    //             }
                    //         }
                    //     }).on('error', function (err) {
                    //         logger.error('get weather went wrong on the request' + err.message);
                    //         callbackInner(err);
                    //     });
                    // } else {
                    //     logger.debug("have userId");
                    //     callbackInner(null);
                    // }

                    var nickNm = encodeURIComponent(input.nickName);
                    var url = "http://" + ssoUrl + "/sso/sso.ajax.php?action=has_nickname&nickname=" + nickNm;
                    restClient.get(url, function (data, response) {
                        if (response.statusCode == 200) {
                            try{
                                var objData = {};
                                objData = JSON.parse(data);
                                if (objData.status == 1) {
                                    // 昵称正常
                                    callbackInner(null, null);
                                } else {
                                    // 宝宝树已经注册了，数据异常
                                    exports.getErrorMsg(objData.error, function(msg){
                                        logger.error(objData+"," + msg);
                                        callbackInner({status: 0, message: msg});
                                    });
                                }
                            } catch(e) {
                                logger.error(e.message);
                                callbackInner({status: 0, message: "网络异常"});
                            }
                        } else {
                            logger.error(e.message);
                            callbackInner({status: 0, message: "网络异常"});
                        }
                    }).on('error', function (err) {
                        logger.error('get weather went wrong on the request' + err.message);
                        callbackInner(err);
                    });
                    /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   end */
                },
                function (callbackInner) {  //注册账号
                    var tempUser = new Users();
                    var args = {
                        data: {
                            username: 'h_' + tempUser._id,
                            password: 'h_' + tempUser._id
                        },
                        headers: {"Content-Type": "application/json"}
                    };
                    /* 宝宝树66小区二期拼团    add SSO注册  llh  20170823   start */
                    input.olduser = 0;
                    exports.registerSsoService(input, clientIp, function(err, registerResult){ // 新
                    // exports.registerSsoService(input, function(err, registerResult){ // 旧
                        if (err) {
                            // 注册失败
                            logger.error(err);
                            callbackInner(err);
                        } else {
                            // 注册成功注册环信，写入本地信息
                            logger.info(registerResult);
                            input.encUserId = registerResult.enc_user_id;
                            var errMsg = ErrorMessage.USER_ALREADY_EXISTS;
                            errMsg.status = 0;
                            restClient.post("http://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/users", args, function (data, response) {
                                if (response.statusCode == 200) {
                                    toolUtil.getInvitationCode(function (err, code) {
                                        tempUser.mobilePhone = input.mobilePhone;
                                        tempUser.userPassword = md5(input.userPassword);
                                        tempUser.invitationCode = code;
                                        tempUser.images = [{imageURL: input.image == null || input.image == '' ? defaultImage : input.image}];
                                        tempUser.huanxinUserName = 'h_' + tempUser._id;
                                        tempUser.nickName = input.nickName;
                                        tempUser.pinyin = pinyin(input.nickName, {style: pinyin.STYLE_NORMAL}).join('').toLowerCase();
                                        tempUser.pinyinShort = pinyin(input.nickName, {style: pinyin.STYLE_FIRST_LETTER}).join('');
                                        tempUser.pinyinSort = tempUser.pinyin + '_' + (new Date()).getTime();
                                        tempUser.regChannelId = input.channelId;
                                        tempUser.deviceId = input.deviceId;
                                        tempUser.encUserId = input.encUserId;
                                        /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 mod wangcan 20170927 start */
                                        tempUser.protocolVersion = newProtocolVersion;
                                        /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 mod wangcan 20170927 end */
                                        input.userId = tempUser._id;
                                        tempUser.save(callbackInner);
                                    });
                                } else {
                                    logger.error(data);
                                    console.log(errMsg);
                                    callbackInner(errMsg);
                                }
                            }).on('error', function (err) {
                                logger.error(err);
                                callbackInner(errMsg);
                            });
                        }
                    });


                    // var errMsg = ErrorMessage.USER_ALREADY_EXISTS;
                    // errMsg.status = 0;
                    // restClient.post("http://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/users", args, function (data, response) {
                    //     if (response.statusCode == 200) {
                    //         toolUtil.getInvitationCode(function (err, code) {
                    //             tempUser.mobilePhone = input.mobilePhone;
                    //             tempUser.userPassword = md5(input.userPassword);
                    //             tempUser.invitationCode = code;
                    //             tempUser.images = [{imageURL: input.image == null || input.image == '' ? defaultImage : input.image}];
                    //             tempUser.huanxinUserName = 'h_' + tempUser._id;
                    //             tempUser.nickName = input.nickName;
                    //             tempUser.pinyin = pinyin(input.nickName, {style: pinyin.STYLE_NORMAL}).join('').toLowerCase();
                    //             tempUser.pinyinShort = pinyin(input.nickName, {style: pinyin.STYLE_FIRST_LETTER}).join('');
                    //             tempUser.pinyinSort = tempUser.pinyin + '_' + (new Date()).getTime();
                    //             tempUser.regChannelId = input.channelId;
                    //             tempUser.deviceId = input.deviceId;
                    //             /*  宝宝树66小区二次改造    add   llh  20170717   start   */
                    //             tempUser.encUserId = input.encUserId;
                    //             input.userId = tempUser._id;
                    //             /*  宝宝树66小区二次改造    add   llh  20170717   end   */
                    //             tempUser.save(callbackInner);
                    //         });
                    //     } else {
                    //         logger.error(data);
                    //         console.log(errMsg);
                    //         callbackInner(errMsg);
                    //     }
                    // }).on('error', function (err) {
                    //     logger.error(err);
                    //     callbackInner(errMsg);
                    // });
                    /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170823   end */
                },
                function (callbackInner) {          //登陆
                    exports.loginService(input.type, input.mobilePhone, input.userPassword, null, clientIp, callbackInner); // 新
                    // exports.loginService(input.type, input.mobilePhone, input.userPassword, null, callbackInner); // 旧
                },
                function (callbackInner) {
                    if (input.thirdParty != null) {
                        exports.accountBindService(input.mobilePhone, input.thirdParty, callbackInner);
                    } else {
                        callbackInner()
                    }
                }
                //function (callbackInner) {
                //    invitationShare.findOne({type: 2, phone: input.mobilePhone}).populate('inviter', 'nickName mobilePhone')
                //        .exec(function (err, result) {
                //            if (result == null) return callbackInner();
                //
                //            Group.findOne({_id: result.groupId}, 'community').populate('community', 'communityName')
                //                .exec(function (err, group) {
                //                    if (group == null) return callbackInner();
                //                    var msg = result.inviter.nickName;
                //                    if (result.inviter.mobilePhone != null) msg += '(' + result.inviter.mobilePhone + ')';
                //                    msg += '邀请你加入' + group.community.communityName + '的家，你要同时入驻这个小区吗？';
                //                    callbackInner(null, {groupMsg: msg, groupCommunityId: group.community._id});
                //                })
                //        })
                //}
            ], callback);

    }
    /*  宝宝树66小区二次改造    add   llh  20170717   end   */
};

/*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170821   start   */
// 宝宝树注册用户到66
exports.registerLocal = function(input, callbackInner){
        var tempUser = new Users();
        var args = {
            data: {
                username: 'h_' + tempUser._id,
                password: 'h_' + tempUser._id
            },
            headers: {"Content-Type": "application/json"}
        };
        restClient.post("http://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/users", args, function (data, response) {
            if (response.statusCode == 200) {
                toolUtil.getInvitationCode(function (err, code) {
                    tempUser.mobilePhone = input.mobilePhone;
                    // tempUser.userPassword = md5(input.userPassword);
                    tempUser.invitationCode = code;
                    tempUser.images = [{imageURL: input.image == null || input.image == '' ? defaultImage : input.image}];
                    tempUser.huanxinUserName = 'h_' + tempUser._id;
                    tempUser.nickName = input.nickName;
                    tempUser.pinyin = pinyin(input.nickName, {style: pinyin.STYLE_NORMAL}).join('').toLowerCase();
                    tempUser.pinyinShort = pinyin(input.nickName, {style: pinyin.STYLE_FIRST_LETTER}).join('');
                    tempUser.pinyinSort = tempUser.pinyin + '_' + (new Date()).getTime();
                    tempUser.regChannelId = input.channelId;
                    tempUser.deviceId = input.deviceId;
                    tempUser.encUserId = input.encUserId;
                    /* 宝宝树66小区三次改造 mod guo.xiaomin 20170928 start */
                    tempUser.protocolVersion = newProtocolVersion;
                    // tempUser.save(callbackInner);
                    // 隐形注册的时候，要保存邀请信息
                    tempUser.save(function (err, saveResult) {
                        logger.debug('隐形注册的时候，要保存邀请信息' + input.mobilePhone);
                        if(saveResult) {
                            exports.saveUserInvitationRecordService(saveResult._id, input.mobilePhone, input.deviceId);
                            callbackInner(err, saveResult);
                        } else {
                            callbackInner(err, saveResult);
                        }
                    });
                    /* 宝宝树66小区三次改造 mod guo.xiaomin 20170928 end */
                });
            } else {
                logger.error(response);
                callbackInner({status:0, message:"网络异常"});
            }
        });
};
// 二次验证
exports.captchValidateService = function (req, callback) {
    var captcha = new Geetest({
        geetest_id: geetest_id,
        geetest_key: geetest_key
    });

    redisClient.get('captchRegister:fallback:'+req.session.id, function (err, value) {
        captcha.validate((value=="false"|| value == null ?false:true), {
            geetest_challenge: req.body.geetest_challenge,
            geetest_validate: req.body.geetest_validate,
            geetest_seccode: req.body.geetest_seccode
        }, function (err, success) {
            if (err) {
                logger.error(err);
                callback({status:false, message:err});
            } else if (!success) {
                // 二次验证失败
                logger.error("验证失败");
                callback({status:false, message:"验证失败"});
            } else {
                logger.debug("验证成功"+'captchRegister:getSmsValidate:'+req.session.id);
                redisClient.set('captchRegister:fallback:'+req.session.id, true);

                redisClient.set('captchRegister:getSmsValidate:'+req.params.deviceId, true);
                redisClient.EXPIRE('captchRegister:getSmsValidate:'+req.params.deviceId, 86400);
                callback(null, success);
            }
        });
    });
};

/*  宝宝树66小区二期拼团    add  登陆极验证 guo.xiaomin  20170926   start   */
// 二次验证
exports.captchValidateLoginService = function (req, callback) {
    var captcha = new Geetest({
        geetest_id: geetest_id,
        geetest_key: geetest_key
    });

    redisClient.get('captchRegister:fallback:'+req.session.id, function (err, value) {
        captcha.validate((value=="false"|| value == null ?false:true), {
            geetest_challenge: req.body.geetest_challenge,
            geetest_validate: req.body.geetest_validate,
            geetest_seccode: req.body.geetest_seccode
        }, function (err, success) {
            if (err) {
                logger.error(err);
                callback({status:false, message:err});
            } else if (!success) {
                // 二次验证失败
                logger.error("验证失败");
                callback({status:false, message:"验证失败"});
            } else {
                logger.debug("验证成功"+'captchRegister:getSmsValidate:'+req.session.id);
                redisClient.set('captchRegister:fallback:'+req.session.id, true);

                callback(null, success);
            }
        });
    });
};
/*  宝宝树66小区二期拼团    add  登陆极验证 guo.xiaomin  20170926   end   */

/*  宝宝树66小区五期安全漏洞-再次修改    add  登陆极验证 guo.xiaomin  20171206   start   */
// 注册二次验证+取得手机号是否注册
exports.captchValidateRegisterNewService = function (req, callback) {
    var captcha = new Geetest({
        geetest_id: geetest_id,
        geetest_key: geetest_key
    });

    var mobilePhone = req.params.mobilePhone; // 手机号
    var deviceId = req.params.deviceId; // 设备ID
    logger.debug("captchValidateNewService:mobilePhone + deviceId..." + mobilePhone + " + " + deviceId);
    redisClient.get('captchRegister:fallback:' + mobilePhone + ":" + deviceId, function (err, value) {
        captcha.validate((value=="false"|| value == null ?false:true), {
            geetest_challenge: req.body.geetest_challenge,
            geetest_validate: req.body.geetest_validate,
            geetest_seccode: req.body.geetest_seccode
        }, function (err, success) {
            if (err) {
                logger.error(err);
                callback({status:false, message:err});
            } else if (!success) {
                // 二次验证失败
                logger.error("验证失败");
                callback({status:false, message:"验证失败"});
            } else {
                logger.debug("captchValidateRegisterNewService success...");
                redisClient.setex('captchRegister:fallback:' + mobilePhone + ":" + deviceId, 86400, true);
                redisClient.setex('captchRegister:getSmsValidate:' + mobilePhone + ":" + deviceId, 86400, true);

                Users.findOne({mobilePhone: mobilePhone}, function (err, result) {
                    var isRegister = result != null;
                    logger.debug("当前手机号是否注册..." + mobilePhone + "@" + isRegister);
                    callback(null, {isRegister: isRegister});
                });
            }
        });
    });
};
/*  宝宝树66小区五期安全漏洞-再次修改    add  登陆极验证 guo.xiaomin  20171206   end   */

/*  宝宝树66小区五期安全漏洞    add  登陆极验证 guo.xiaomin  20171116   start   */
// 注册,忘记密码,二次验证
exports.captchValidateNewService = function (req, callback) {
    var captcha = new Geetest({
        geetest_id: geetest_id,
        geetest_key: geetest_key
    });

    var mobilePhone = req.params.mobilePhone; // 手机号
    var deviceId = req.params.deviceId; // 设备ID
    logger.debug("captchValidateNewService:mobilePhone + deviceId..." + mobilePhone + " + " + deviceId);
    redisClient.get('captchRegister:fallback:' + mobilePhone + ":" + deviceId, function (err, value) {
        captcha.validate((value=="false"|| value == null ?false:true), {
            geetest_challenge: req.body.geetest_challenge,
            geetest_validate: req.body.geetest_validate,
            geetest_seccode: req.body.geetest_seccode
        }, function (err, success) {
            if (err) {
                logger.error(err);
                callback({status:false, message:err});
            } else if (!success) {
                // 二次验证失败
                logger.error("验证失败");
                callback({status:false, message:"验证失败"});
            } else {

                redisClient.setex('captchRegister:fallback:' + mobilePhone + ":" + deviceId, 86400, true);
                redisClient.setex('captchRegister:getSmsValidate:' + mobilePhone + ":" + deviceId, 86400, true);
                callback(null, success);
            }
        });
    });
};

// 登陆二次验证
exports.captchValidateLoginNewService = function (req, callback) {
    var captcha = new Geetest({
        geetest_id: geetest_id,
        geetest_key: geetest_key
    });

    var mobilePhone = req.params.mobilePhone; // 手机号
    var deviceId = req.params.deviceId; // 设备ID
    logger.debug("captchValidateLoginNewService:mobilePhone + deviceId..." + mobilePhone + " + " + deviceId);
    redisClient.get('captchRegister:fallback:' + mobilePhone + ":" + deviceId, function (err, value) {
        captcha.validate((value=="false"|| value == null ?false:true), {
            geetest_challenge: req.body.geetest_challenge,
            geetest_validate: req.body.geetest_validate,
            geetest_seccode: req.body.geetest_seccode
        }, function (err, success) {
            if (err) {
                logger.error(err);
                callback({status:false, message:err});
            } else if (!success) {
                // 二次验证失败
                logger.error("验证失败");
                callback({status:false, message:"验证失败"});
            } else {
                logger.debug("captchValidateLoginNewService success...");
                logger.debug("验证成功"+'captchRegister:fallback:' + mobilePhone + ":" + deviceId);
                redisClient.setex('captchRegister:fallback:' + mobilePhone + ":" + deviceId, 86400, true);

                callback(null, success);
            }
        });
    });
};
/*  宝宝树66小区五期安全漏洞    add  登陆极验证 guo.xiaomin  20171116   end   */

// 美囤token取得
exports.getMeitunTokenService = function (params, callbackInner) {
    // 美囤token取得
    var url = "https://" + meitunUrl + "/newapi/passport/signinForLoginStrCondense?"
        + "loginstr="+params.loginstr
        + "&platform="+params.platform
        + "&timestamp="+params.timestamp
        + "&signature="+params.signature;
    logger.debug(url);
    logger.debug(params);
    restClient.get(url, function (data, response) {
        logger.info("response.statusCode..." + response.statusCode);
        if (response.statusCode == 200) {
            try {
                var objData = {};
                objData = JSON.parse(data);
                var status = objData.rtn_code;
                if ("0" == status) {
                    // input.encUserId = objData.data.enc_user_id;
                    // logger.info(objData);
                    logger.debug(objData.data);
                    logger.debug('exports.getMeitunTokenService success 001...');
                    callbackInner(null, objData.data.token);
                } else {
                    logger.error(objData);
                    logger.debug('exports.getMeitunTokenService error 001...');
                    callbackInner({status: 0, message: "网络异常"});
                }
            } catch (e) {
                logger.error(e.message);
                logger.debug('exports.getMeitunTokenService error 002...');
                callbackInner({status: 0, message: "网络异常"});
            }
        } else {
            logger.error(response);
            logger.debug('exports.getMeitunTokenService error 003...');
            callbackInner({status: 0, message: "网络异常"});
        }
    }).on('error', function (err) {
        logger.debug('exports.getMeitunTokenService error 004...');
        logger.error('get weather went wrong on the request' + err.message);
        callbackInner(err);
    });
};

/*  宝宝树66小区 宝宝树自动登录优化 add  小区切换 luolh  20171101   start   */
// 宝宝树用户信息取得
exports.getBabytreeUserInfoService = function (encUserId, callbackInner) {
    // 注册到宝宝树
    var params = [{name:"action", value:"get_user_data"}
        ,{name:"enc_user_id", value:encUserId}];

    var url = "http://" + ssoUrl + "/sso/meitun.sso.php";
    exports.getSsoTokenTailService(params, function(urlTail){
        if (params.length > 0) {
            url += "?" + urlTail;
        }
        logger.debug(url);
        restClient.get(url, function (data, response) {
            if (response.statusCode == 200) {
                try {
                    var objData = {};
                    objData = JSON.parse(data);
                    var status = objData.status;
                    if (1 == status) {
                        logger.info(objData);
                        callbackInner(null, objData.data);
                    } else {
                        // 数据异常
                        exports.getErrorMsg(objData.error, function(msg){
                            logger.error(objData+"," + msg);
                            callbackInner({status: 0, message: msg});
                        });
                    }
                } catch (e) {
                    logger.error(e.message);
                    callbackInner({status: 0, message: "网络异常"});
                }
            } else {
                callbackInner({status: 0, message: "网络异常"});
            }
        }).on('error', function (err) {
            logger.error('get weather went wrong on the request' + err.message);
            callbackInner(err);
        });
    });
};
/*  宝宝树66小区 宝宝树自动登录优化 add  小区切换 luolh  20171101   end   */

// SSO注册接口
exports.registerSsoService = function (input, clientIp, callbackInner) { // 新
// exports.registerSsoService = function (input, callbackInner) { // 旧
    // 注册到宝宝树
    var nickNm = input.nickName;
    var params = [{name:"action", value:"create_user_by_mobile"}
        ,{name:"phone", value:input.mobilePhone}
        ,{name:"password",value:input.userPassword}
        ,{name:'client_ip', value: clientIp}
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170902   start   */
        // ,{name:"nickname", value:nickNm} // 旧
        // 防止昵称重复
        ,{name:"nickname", value:'' + nickNm + toolUtil.getRandomNumberByNum(6)} // 新
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170902   end   */
        ,{name:"olduser", value : input.olduser}
        ,{name:"type", value : "66"}];

    var url = "http://" + ssoUrl + "/sso/meitun.sso.php";
        exports.getSsoTokenTailService(params, function(urlTail){
            if (params.length > 0) {
                url += "?" + urlTail;
            }
            // logger.debug(url);
            restClient.get(url, function (data, response) {
                if (response.statusCode == 200) {
                    try {
                        var objData = {};
                        objData = JSON.parse(data);
                        var status = objData.status;
                        if (1 == status) {
                            // input.encUserId = objData.data.enc_user_id;
                            logger.info(objData);
                            callbackInner(null, objData.data);
                        } else {
                            // 宝宝树已经注册了，数据异常
                            exports.getErrorMsg(objData.error, function(msg){
                                logger.error(objData+"," + msg);
                                callbackInner({status: 0, message: msg});
                            });
                        }
                    } catch (e) {
                        logger.error(e.message);
                        callbackInner({status: 0, message: "注册异常"});
                    }
                } else {
                    callbackInner({status: 0, message: "注册异常"});
                }
            }).on('error', function (err) {
                logger.error('get weather went wrong on the request' + err.message);
                callbackInner(err);
            });
        });
};

exports.updateSsoPassword = function (encUserId, password, clientIp, callbackInner) { // 新
// exports.updateSsoPassword = function (encUserId, password, callbackInner) { // 旧
    // 修改密码到宝宝树
    var params = [
        {name:"action", value:"change_password"}
        ,{name:"enc_user_id", value:encUserId}
        ,{name:"password", value:password}
        ,{name:'client_ip', value: clientIp}];

    var url = "http://" + ssoUrl + "/sso/meitun.sso.php";
    exports.getSsoTokenTailService(params, function(urlTail){
        if (params.length > 0) {
            url += "?" + urlTail;
        }
        // logger.info(url);
        restClient.get(url, function (data, response) {
            if (response.statusCode == 200) {
                try {
                    var objData = {};
                    logger.debug('JSON.parse start...');
                    objData = JSON.parse(data);
                    logger.debug('JSON.parse end...');
                    var status = objData.status;
                    logger.debug('status...' + status);
                    if (status == 1) {
                        logger.info(objData);
                        callbackInner(null, objData.data);
                    } else {
                        // 宝宝树已经注册了，数据异常
                        exports.getErrorMsg(objData.error, function(msg){
                            logger.error(objData);
                            logger.error(msg);
                            callbackInner({status: 0, message: msg});
                        });
                    }
                } catch (e) {
                    logger.error(e.message);
                    callbackInner({status: 0, message: "密码修正失败"});
                }
            } else {
                callbackInner({status: 0, message: "密码修正失败"});
            }
        }).on('error', function (err) {
            logger.error('get weather went wrong on the request' + err.message);
            callbackInner(err);
        });
    });
};

exports.getErrorMsg = function (errCode, callbackInner) {
    var msg = "";
    switch(errCode)
    {
        case -1:
            msg="返回失败";
            break;
        case 1:
            msg="返回成功";
            break;
        case 2:
            msg="没有数据";
            break;
        case 3:
            msg="未知错误";
            break;
        case 4:
            msg="token错误";
            break;
        case 5:
            msg="ip限制";
            break;
        case 6:
            msg="不安全的访问，没使用https";
            break;
        case 7:
            msg="园丁账户,请宝宝树首页登录";
            break;
        case 8:
            msg="您操作次数太多，为了您账号的安全，锁定帐号一小时";
            break;
        case 10:
            msg="密码长度无效";
            break;
        case 20:
            msg="邮箱已经存在";
            break;
        case 21:
            msg="邮箱不存在";
            break;
        case 22:
            msg="邮箱格式错误";
            break;
        case 30:
            msg="宝宝姓名格式错误";
            break;
        case 31:
            msg="宝宝生日格式错误";
            break;
        case 40:
            msg="已经登录";
            break;
        case 41:
            msg="邮箱和密码不匹配";
            break;
        case 42:
            msg="邮箱或密码为空";
            break;
        case 43:
            msg="邮箱格式错误";
            break;
        case 44:
            msg="密码长度错误";
            break;
        case 45:
            msg="连续注册过多，注册被禁止";
            break;
        case 46:
            msg="登录时手机号格式错误";
            break;
        case 47:
            msg="登录密码格式错误";
            break;
        case 50:
            msg="昵称格式错误";
            break;
        case 51:
            msg="昵称太短";
            break;
        case 52:
            msg="昵称太长";
            break;
        case 53:
            msg="has special charactor";
            break;
        case 54:
            msg="昵称无效";
            break;
        case 55:
            msg="昵称被屏蔽";
            break;
        case 56:
            msg="昵称被锁定";
            break;
        case 57:
            msg="昵称已经存在";
            break;
        case 58:
            msg="昵称不存在";
            break;
        case 60:
            msg="邮箱和密码不匹配";
            break;
        case 61:
            msg="邮箱或密码为空";
            break;
        case 62:
            msg="邮箱格式错误";
            break;
        case 63:
            msg="密码长度错误";
            break;
        case 64:
            msg="地区必须是数字";
            break;
        case 65:
            msg="性别错误";
            break;
        case 66:
            msg="是否有宝宝数据错误";
            break;
        case 67:
            msg="宝宝生日格式错误";
            break;
        case 68:
            msg="邮箱用户已经存在";
            break;
        case 69:
            msg="昵称已经存在";
            break;
        case 70:
            msg="手机号为空";
            break;
        case 71:
            msg="手机号格式不正确";
            break;
        case 72:
            msg="手机号已经注册";
            break;
        case 80:
            msg="cookie错误";
            break;
        case 81:
            msg="绑定失败";
            break;
        case 82:
            msg="重复绑定";
            break;
        case 83:
            msg="验证码错误";
            break;
        case 90:
            msg="微信号为空";
            break;
        case 91:
            msg="微信号存在";
            break;
        case 92:
            msg="手机号不存在";
            break;
        case 93:
            msg="绑定微信号失败";
            break;
        case 94:
            msg="绑定手机号失败";
            break;
        case 95:
            msg="微信号不存在";
            break;
        case 96:
            msg="登录密码为空";
            break;
        case 97:
            msg="创建微信账号失败";
            break;
        case 98:
            msg="密码不能少于8位";
            break;
        case 99:
            msg="密码不能超过30位";
            break;
        case 100:
            msg="密码至少为8位，且必须采用数字+英文或者符号组合";
            break;
    }
    callbackInner(msg);
};

// 取得sso token token
// param = {name:'',value:''}
exports.getSsoTokenTailService = function (params, callbackInner) {
    var urlTail = "";
    // 顺番加参数
    for (var i = 0; i < params.length; i++) {
        if (i == 0) {
            urlTail+= (params[i].name + "=" + encodeURIComponent(params[i].value));
        } else {
            urlTail+= ("&"+params[i].name + "=" + encodeURIComponent(params[i].value));
        }
    }
    var token = "";
    // 排序
    if (params.length > 0) {
        // 排序后，取得token
        params = params.sort(function(a,b){
            if (a.name > b.name) {
                // logger.info("a.name > b.name:" + a.name +">" +b.name);
                return 1;
            } else {
                // logger.info("a.name <= b.name:" + a.name + "<=" + b.name);
                return -1;
            }
        });
        // logger.info(params);
        var token = "";
        for (var i = 0; i < params.length; i++) {
            if (i == 0) {
                token+= (params[i].name + "=" + encodeURIComponent(params[i].value));
            } else {
                token+= ("&"+params[i].name + "=" + encodeURIComponent(params[i].value));
            }
        }
        // logger.info("md5前:"+token+ssoPriKey);
        token = md5(token + ssoPriKey);
        // logger.info("md5后:"+token);
    }
    urlTail = urlTail + "&token="+ token;
    callbackInner(urlTail);
};

/*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170821   end   */
/**
 * 生成新手任务
 */
exports.createNoviceTaskService = function (userId) {
    var temp = new UserTask();
    /*  宝宝树66小区二次改造    mod   chenf  20170717   start   */
    /*temp.name = '新手礼包';*/
    temp.name = '新手任务';
    /*temp.reward = 16;*/
    /*  宝宝树66小区二次改造    mod   chenf  20170717   end   */
    temp.type = 'novice';
    temp.deadline = moment().add(15, 'day').toDate();
    temp.user = userId;
    temp.subTask = [
        /*  宝宝树66小区二次改造    mod   chenf  20170717   start   */
        /*{
         title: '给邻居点个赞吧~',
         desc: '给TA个最暖心的鼓励吧~',
         action: 'praise'
         },
         {
         title: '回复一条邻里问问吧~',
         desc: '大家正迫切的需要你的帮助哦~',
         action: 'reply'
         },
         {
         title: '发布一条邻里问问呗~',
         desc: '有事问邻居，也许邻居能帮到你哦',
         action: 'release'
         }*/

        {
            title: '发布说说',
            desc: '随便说几句吧',
            action: 'release'
        },
        {
            title: '点赞',
            desc: '予人玫瑰手有余香',
            action: 'praise'
        },
        {
            title: '评论',
            desc: '给心仪的闲置留个言',
            action: 'comment'
        },
        {
            title: '分享',
            desc: '让更多人认识我',
            action: 'share'
        },
        {
            title: '邀请',
            desc: '人多可以解锁更多好玩的哦',
                action: 'invitation'
        }
        /*  宝宝树66小区二次改造    mod   chenf  20170717   end   */
    ];
    temp.save(function (err, result) {
        if (err) {
            logger.error('Failed to createNoviceTask --- ' + userId + '--' + err.message);
        } else {
            //toolUtil.putMessageBusinessMQ({msgType: 'novice_pack', uid: userId, taskId: result._id});
        }
    });
};

/**
 * 账号绑定
 * @param mobilePhone
 * @param third
 * @param callback
 */
exports.accountBindService = function (mobilePhone, third, callback) {
    Users.update({mobilePhone: mobilePhone}, {$push: {thirdParty: third}}, callback)
};


/**
 * 登陆service
 * @param mobilePhone   电话号码
 * @param password      密码
 * @param thirdId       第三方id
 * @param callback
 */
exports.loginService = function (type, mobilePhone, password, thirdId, clientIp, callback) { // 新
// exports.loginService = function (type, mobilePhone, password, thirdId, callback) { // 旧

    var opt = {};
    if (mobilePhone != null)
        opt.mobilePhone = mobilePhone;
    if (password != null)
        opt.userPassword = md5(password);
    if (mobilePhone == null && thirdId != null)
        opt.wechatId = thirdId.toLowerCase();

    var user;
    async.series([
        /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   start */
        function (callbackInner) {
            // 登录极验证,返回loginStr
            var params = [
                {name:'action', value:'mobile_login'},
                {name:'phone_number', value:mobilePhone},
                {name:'password', value:password},
                {name:'client_ip', value: clientIp}
            ];
            // var url = "http://"+ssoUrl;
            var url = "http://" + ssoUrl + "/sso/meitun.sso.php";
            exports.getSsoTokenTailService(params, function(urlTail) {
                if (params.length > 0) {
                    url += "?" + urlTail;
                }
                logger.info(url);
                restClient.get(url, function (data, response) {
                    if (response.statusCode == 200) {
                        logger.debug(data);
                        var objData = JSON.parse(data);
                        if (objData.status == 1) {
                            // 正常
                            var loginStr = objData.data.login_string;
                            if (!loginStr) {
                                logger.error("loginStr为空:"+objData);
                            } else {
                                // 根据loginStr取得token
                                var platform = "";
                                if (type == "android") {
                                    platform = "9";
                                } else {
                                    platform = "8";
                                }
                                var params = {
                                    loginstr : loginStr,
                                    platform : platform,
                                    timestamp : moment().format('YYYYMMDDHHmmss'),
                                    signature : "none"
                                };
                                logger.debug(params);
                                exports.getMeitunTokenService(params, function(err, tokenResult) {
                                    if (err) {
                                        logger.error(err);
                                        callbackInner(err);
                                    } else {
                                        var loginTokenResult = {
                                            loginStr : loginStr,
                                            token : tokenResult
                                        };
                                        logger.debug(loginTokenResult);
                                        callbackInner(null, loginTokenResult);
                                    }
                                });
                            }
                        } else {
                            exports.getErrorMsg(objData.error, function(msg){
                                logger.error(objData+"," + msg);
                                callbackInner({status: 0, message: msg});
                            });
                        }
                    } else {
                        logger.error(data);
                        callbackInner({status:0,message:"网络异常"});
                    }
                }).on('error', function (err) {
                    logger.error(err);
                    callbackInner(err);
                });
            });

        },
        /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   end */
        function (callbackInner) {//用户资料
            Users.findOne(opt, '_id frozenOrNot mobilePhone birthDate nickName encUserId gender images hobbies communityWay ' +
                //Users.findOne(opt, '_id frozenOrNot mobilePhone birthDate nickName gender images hobbies communityWay ' +
                'community homeTown.province homeTown.city huanxinUserName appSetting userType speciality ' +
                'userPortrait job school authenticationStatus roomUnit roomNumber showUnit invitationCode children userRole dateCreated')
                .populate('userPortrait', 'portraitURL value')
                .populate('community', '_id communityName communityName_en_US pinyin communityAddress communityLogo unitSwitch')
                .populate('homeTown.province', '_id name')
                .populate('homeTown.city', '_id name')
                .populate('hobbies', '_id value')
                .exec(function (err, result) {
                    if (err) {
                        callbackInner(err)
                    } else {
                        if (result == null) {
                            callbackInner(ErrorMessage.INVALID_LOGIN_PASSWORD)
                        } else if (result.frozenOrNot) {
                            callbackInner(ErrorMessage.ACCOUNT_FROZEN)
                        } else {
                            result._doc.roomUnit = !isNaN(result.roomUnit) ? result.roomUnit + '单元' : result.roomUnit;

                            result._doc.communityWay = result.communityWay ? result.communityWay : 1;

                            user = result;

                            // if (result.community) {
                            //
                            //     var comm = result.community.toJSON();
                            //
                            //     comm.communityName_en_US = (comm.pinyin) ?
                            //         comm.pinyin.toUpperCase() : pinyin(comm.communityName, {style: pinyin.STYLE_NORMAL}).join('').toUpperCase();
                            //
                            //     result._doc.community = comm;
                            // }

                            callbackInner(null, result);
                        }
                    }
                });
        },
        function (callbackInner) {//权限列表
            var role = user.authenticationStatus ? 'vip' : 'vip';
            var auth = [];
            roleAction.find({role: role}).populate('action', 'tag').exec(function (err, results) {
                if (results != null) {
                    results.forEach(function (temp) {
                        auth.push(temp.action.tag);
                    })
                }
                callbackInner(err, auth);
            });
        },
        function (callbackInner) {//V认证状态 0,未提交;1,已认证;2,审核中
            if (user && user.community) {
                userAuthentication.findOne({
                    user: user._id,
                    isValid: true,
                    community: user.community._id
                }, 'status', function (err, result) {
                    var vStatus = result ? (result.status ? 1 : 2) : 0;
                    callbackInner(err, vStatus);
                })
            } else {
                callbackInner(null, 0);
            }
        },
        function (callbackInner) {//今天签到状态
            var key = 'app:signin:' + moment().format('YYYYMMDD');

            redisClient.SISMEMBER(key, user._id + '', function (err, result) {
                callbackInner(null, result == 1);
            });
        },
        function (callbackInner) {
            UserTask.findOne({
                user: user._id,
                type: 'novice',
                deadline: {$gt: new Date()},
                'subTask.status': false
            }, 'name subTask', function (err, task) {
                callbackInner(null, task != null);
            })
        }
    ], function (err, results) {
        if (err) {
            callback(err)
        } else {
            toolUtil.setUserByToken(user._id, true);

            user._doc['token'] = toolUtil.getUserTokenById(user._id);
            /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   start */
            user._doc['loginStr'] = results[0].loginStr;
            user._doc['meitunToken'] = results[0].token;

            user._doc['auth'] = results[2];
            user._doc['vStatus'] = results[3];
            user._doc['isSignIn'] = results[4];
            user._doc['taskFlag'] = results[5];

            // user._doc['auth'] = results[1];
            // user._doc['vStatus'] = results[2];
            // user._doc['isSignIn'] = results[3];
            // user._doc['taskFlag'] = results[4];
            /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   end */
            callback(null, user);
        }
    });
};

/**
 * 第三方绑定确认(绑定已注册手机号)
 * @param input
 * @param callback
 */
exports.thirdPartyBindService = function (input, clientIp, callback) { // 新
// exports.thirdPartyBindService = function (input, callback) { // 旧
    async.series([
        function (callbackInner) {      //验证码校验
            exports.checkVerificationCodeService(input.mobilePhone, input.type, input.code, callbackInner);
        },
        function (callbackInner) {      //绑定账号
            exports.accountBindService(input.mobilePhone, input.thirdParty, callbackInner);
        },
        function (callbackInner) {
            /*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170826  start   */
            exports.loginService(input.type, input.mobilePhone, null, null, clientIp, callbackInner); // 新
            // exports.loginService(input.type, input.mobilePhone, null, null, callbackInner); // 旧
            // exports.loginService(input.mobilePhone, null, null, callbackInner);
            /*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170826   end   */
        }
    ], callback)
};

/**
 * 第三方登陆
 * @param id       第三方id
 * @param callback
 */
  exports.thirdPartyLoginService = function (id, clientIp, callback) { // 新
  // exports.thirdPartyLoginService = function (id, callback) { // 旧
    Users.findOne({$or: [{wechatId: id.toLowerCase()}, {'thirdParty.id': id}]}, 'mobilePhone', function (err, result) {
        if (result == null) {
            callback(null, {isRegister: false});
        } else {
            exports.loginService(result.mobilePhone, null, id, clientIp, function (err, user) { // 新
            // exports.loginService(result.mobilePhone, null, id, function (err, user) { // 旧
                if (err) {
                    callback(err)
                } else {
                    user._doc['isRegister'] = true;
                    callback(null, user);
                }
            });
        }
    })
};


/**
 * 获取开通城市列表
 * @param lat    纬度
 * @param lng    经度
 * @param token
 * @param callback
 */
exports.getCityListService = function (lat, lng, token, callback) {
    exports.getCityIdByLocationService(lat, lng, token, function (err, value) {
        communityCity.find({}, '-_id name cityId').sort({dateCreated: 1}).exec(function (err, result) {

            async.each(result, function (temp, cb) {
                Regions.find({parentId: temp.cityId}, 'name type', function (err, counties) {

                    if (counties != null) {
                        counties.forEach(function (t) {
                            t._doc.isSelect = t.name == value.countyName
                        });
                        temp._doc.countyList = counties;
                    }
                    temp._doc.isSelect = temp.cityId + '' == value.city + '';
                    cb();
                })
            }, function (err) {
                callback(null, {cityList: result});
            });
        })
    })
};

exports.getHotCityListService = function (lat, lng, token, callback) {
    exports.getCityIdByLocationService(lat, lng, token, function (err, value) {
        async.parallel([
            function (callbackInner) {
                Regions.findOne({_id: value.city, type: 'city'}, 'name pinyin', callbackInner)
            },
            function (callbackInner) {
                var hotList = ['上海', '北京', '广州', '深圳'];
                Regions.find({type: 'city', name: {$in: hotList}}, 'name pinyin', function (err, result) {
                    result.map(function(a) {
                        a.pinyin = a.pinyin.replace(/shi$/, '');

                    });
                    result.sort(function (a, b) {
                        return hotList.indexOf(a.name) - hotList.indexOf(b.name)
                    });
                    callbackInner(err, result)
                });
            }
        ], function (err, result) {
            var data = {
                hotList: result[1]
            };
            if (result[0] != null && lat != '0' && lng != '0') {
                result[0].pinyin = result[0].pinyin.replace(/shi$/, '');
                data.loc = result[0]
            }
            callback(err, data)
        })
    })
};

/**
 * 获取小区列表
 * @param lat       纬度
 * @param lng       经度
 * @param cityId    城市id
 * @param page      页码
 * @param token
 * @param callback
 */
exports.getCommunityListService = function (lat, lng, cityId, page, token, callback) {
    exports.getCityIdByLocationService(lat, lng, token, function (err, value) {
        var index = Number(page) * listPageSize;

        var opt = {
            isValid: true,
            communityType: {$ne: 0},
            cityId: cityId != '0' ? cityId : value.city
        };

        var sort = {};
        if (lat == '0' || cityId != value.city) {
            sort.pinyin = 1;
        } else {
            opt.location = {$nearSphere: [lng, lat]}
        }

        community.find(opt, 'communityName communityName_en_US location pinyin')
            .skip(index).limit(listPageSize).sort(sort).exec(function (err, results) {
                results.forEach(function (result) {
                    var dis = '';
                    if (lat != '0' && lng != '0' && cityId == value.city) {
                        var distance = geolib.getDistance(
                            {latitude: lat, longitude: lng},
                            {latitude: result.location.latitude, longitude: result.location.longitude}
                        );
                        if (distance > 1000) {
                            var aa = distance / 1000;
                            dis = aa.toFixed(1) + 'km';
                        } else {
                            dis = distance + 'm';
                        }
                    }
                    result._doc.distance = dis;
                });
                callback(err, results);
            });
    });
};

/**
 * 搜索小区
 * @param lat
 * @param lng
 * @param cityId
 * @param keyword
 * @param token
 * @param callback
 */
exports.searchCommunityService = function (lat, lng, cityId, opt, token, callback) {
    exports.getCityIdByLocationService(lat, lng, token, function (err, value) {

        opt.cityId = cityId != '0' ? cityId : value.city;
        opt.isValid = true;
        opt.communityType = {$ne: 0};


        community.find(opt,
        //     {
        //     cityId: cityId != '0' ? cityId : value.city,
        //     isValid: true,
        //     communityType: {$ne: 0},
        //     communityName: new RegExp(keyword)
        // },
            'communityName location communityName_en_US pinyin', function (err, results) {
            results.forEach(function (result) {
                var dis = '';
                if (lat != '0' && lng != '0') {
                    var distance = geolib.getDistance(
                        {latitude: lat, longitude: lng},
                        {latitude: result.location.latitude, longitude: result.location.longitude}
                    );
                    if (distance > 1000) {
                        var aa = distance / 1000;
                        dis = aa.toFixed(1) + 'km';
                    } else {
                        dis = distance + 'm';
                    }
                }

                result._doc.distance = dis;
                result._doc.order = distance;
            });

            results.sort(function (a, b) {
                return a._doc.order - b._doc.order;
            });

            callback(null, results);
        })
    });
};

/**
 * 根据经纬度获取城市id
 * @param lat
 * @param lng
 * @param token
 * @param callback
 */
exports.getCityIdByLocationService = function (lat, lng, token, callback) {

    var key = 'app:user:location:catch:' + token;

    redisClient.get(key, function (err, value) {
        if (value == null) {
            var cityName = '上海';
            var countyName = '黄浦区';

            communityCity.findOne({name: cityName}, function (err, city) {
                restClient.get('http://api.map.baidu.com/geocoder/v2/?ak=AvRqTglpaKICTZ5iwyn06KZj&output=json&pois=0&location='
                    + lat + ',' + lng, function (data, response) {
                    data = JSON.parse(data);
                    if (response.statusCode == 200 && data.status == 0) {
                        if (data.result.addressComponent.city != '') {
                            cityName = data.result.addressComponent.city;
                            cityName = cityName.substr(0, cityName.length - 1);
                            countyName = data.result.addressComponent.district;
                        }
                    }

                    Regions.findOne({name: new RegExp('^' + cityName), type: 'city'}, function (err, result) {
                        var args = [key, 'city', result ? result.cityId + '' : city.cityId + '', 'countyName', countyName];
                        redisClient.HMSET(args, function (err, res) {
                        });
                        redisClient.EXPIRE(key, 86400);

                        callback(null, {city: result ? result._id : city.cityId, countyName: countyName});
                    });

                }).on('error', function (err) {
                    logger.error('getCityIdByLocationService--' + err.message);

                    redisClient.set(key, city.cityId);
                    redisClient.EXPIRE(key, 86400);

                    callback(null, {city: city.cityId, countyName: countyName});
                });
            })
        } else {
            callback(null, value)
        }
    });
};

/**
 * v认证提交单元号、房号信息
 * @param token
 * @param input
 * @param callback
 */
exports.postVerifiedProfileService = function (token, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {

            var data = {
                roomUnit: input.roomUnit,
                roomNumber: input.roomNumber
            };

            //if (input.type != 0) {
            //    data['$set'] = {userRole: [input.type]}
            //} else {
            //    data['$set'] = {userRole: []}
            //}


            Users.update({_id: user._id}, data, callback)
        }
    })
};


/**
 * 定位认证
 * @param token
 * @param communityId   小区id
 * @param lat           纬度
 * @param lng           经度
 * @param callback
 */
exports.locationVerifiedService = function (token, communityId, lat, lng, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED);
        } else {
            community.findOne({_id: communityId}, 'location city communityName', function (err, result) {
                if (result == null) {
                    callback({message: '小区不存在'})
                } else {

                    var locationMsg = '';
                    var locationDesc = '';

                    var distanceFlag = false;

                    async.series([
                        function (callbackInner) {
                            restClient.get('http://api.map.baidu.com/geocoder/v2/?ak=AvRqTglpaKICTZ5iwyn06KZj&location='
                                + lat + ',' + lng + '&output=json', function (data, response) {
                                data = JSON.parse(data);
                                if (response.statusCode == 200 && data.status == 0) {
                                    var city = data.result.addressComponent.city;
                                    var desc = data.result.sematic_description;

                                    locationDesc = desc;
                                    if (city.indexOf(result.city) == 0 && desc.indexOf(result.communityName) != -1) {
                                        locationMsg = '匹配小区名称认证';
                                        callbackInner();
                                    } else {
                                        distanceFlag = true;
                                        callbackInner();
                                    }
                                } else {
                                    distanceFlag = true;
                                    callbackInner()
                                }
                            }).on('error', function (err) {
                                distanceFlag = true;
                                callbackInner();
                            });
                        },
                        function (callbackInner) {
                            if (distanceFlag) {
                                var distance = geolib.getDistance(
                                    {latitude: lat, longitude: lng},
                                    {latitude: result.location.latitude, longitude: result.location.longitude}
                                );

                                if (distance > LOCATION_VERIFIED) {
                                    locationMsg = '地址认证失败';
                                    callbackInner({message: '地址认证失败'})
                                } else {
                                    locationMsg = '小区范围认证';
                                    callbackInner();
                                }
                            } else {
                                callbackInner();
                            }
                            var temp = new locationV();
                            temp.user = user._id;
                            temp.community = result.communityName;
                            temp.lat = Number(lat);
                            temp.lng = Number(lng);
                            temp.message = locationMsg;
                            temp.desc = locationDesc;
                            if (distance) temp.distance = distance;
                            temp.save();
                        },
                        function (callbackInner) {//认证记录
                            userAuthentication.update({
                                user: user._id,
                                community: communityId,
                                isValid: true
                            }, {
                                status: true,
                                promotionCode: '定位认证',
                                dateCreated: new Date()
                            }, {upsert: true}, callbackInner)
                        },
                        function (callbackInner) {//更新状态
                            Users.update({_id: user._id}, {authenticationStatus: true}, function (err, result) {
                                toolUtil.setUserByToken(token);
                                callbackInner(null, user);
                            })
                        },
                        function (callbackInner) {//权限列表
                            var data = [];
                            roleAction.find({role: 'vip'}).populate('action', 'tag').exec(function (err, results) {
                                if (results != null) {
                                    results.forEach(function (temp) {
                                        data.push(temp.action.tag);
                                    })
                                }
                                var res = {
                                    auth: data,
                                    vStatus: 1
                                };
                                callbackInner(err, res);
                            });
                        }
                    ], callback);
                }
            })
        }
    })
};

/**
 * v认证成功后发放奖励
 * @param userId
 */
exports.sendVerifiedSuccessfulRewardsService = function (userId) {
    Users.findOne({_id: userId}, 'community huanxinUserName invitedBy').populate('community', '_id communityName')
        .exec(function (err, result) {
            //v认证奖励
            userController.authenticationAddScore(userId, result.community._id);

            //v认证小6发送消息
            toolUtil.pushCustomerServiceMessage(result, "你好，你的V认证已经通过，我们将为V用户提供更多，更好的服务，也让你在小区中更与众不同。");

        })
};

exports.sendInviteRewardService = function (userId, invite) {


    //注册加分
    toolUtil.hessianInvokeAddScore(userId, 39, null, function (value) {
    });


    Users.findOne({_id: userId}, 'community huanxinUserName invitedBy mobilePhone nickName').populate('community', '_id communityName cityId')
        .exec(function (err, result) {

            //新人欢迎贴
            mutualAidService.createWelcomeQuestionService(result);

            UserInvitationRecord.findOne({type: 2, phone: result.mobilePhone}, function (err, inv) {
                if (inv != null) {
                    if (invite == null) {
                        groupService.inviteUserService(inv.inviter, {
                            userId: userId,
                            groupId: inv.groupId
                        }, function () {
                        })
                    } else {
                        groupService.registerJoinGroupService(userId, inv.groupId, inv.inviter);
                    }
                }
            });

            //邀请人奖励
            if (result.invitedBy != null) {

                //放入周排行榜
                var key = 'rank:invitation:' + moment().startOf('isoWeek').format('YYYYMMDD');
                redisClient.ZINCRBY(key, 1, result.invitedBy);

                //放入总排行榜
                var totalKey = 'rank:invitation:total';
                redisClient.ZINCRBY(totalKey, 1, result.invitedBy);


                //发放奖励
                mysqlUtil.generateUserVoucher(result.invitedBy, 2, userId, function (err, result) {
                    if (err) {
                        logger.error(err.message);
                    } else {
                        userInvitation.update({invitee: userId}, {
                            score: result.value,
                            dateLastModified: new Date(),
                            type: result.type
                        }).exec();
                    }
                });

                if (invite == null) {
                    //发送通知
                    var message = {
                        msgType: 'invite',
                        userId: result.invitedBy,
                        inviteUserId: userId
                    };
                    toolUtil.putMessageBusinessMQ(message);
                }

                //建立相互关注
                userService.eachOtherFollowupService(userId, result.invitedBy);
            }
        })
};

/**
 * 保存邀请记录
 * @param userId
 * @param mobilePhone
 * @param deviceId
 */
exports.saveUserInvitationRecordService = function (userId, mobilePhone, deviceId) {
    invitationShare.findOne({phone: mobilePhone}, function (err, result) {
        if (result != null) {
            var temp = new userInvitation();
            temp.invitee = userId;
            temp.inviter = result.inviter;
            temp.save();
            Users.update({_id: userId}, {$set: {invitedBy: result.inviter}}).exec();

            var temp1 = new deviceCodeBind();
            temp1.invitationCode = result.invitationCode;
            temp1.deviceId = deviceId;
            temp1.user = userId;
            temp1.save();

            /*  宝宝树66小区二次改造    add   chenf  20170714   start   */
            taskService.finishTaskService(result.inviter, 'invitation', function () {
            });
            /*  宝宝树66小区二次改造    add   chenf  20170714   end   */

        }
    })
};

exports.getMyInvitationPartRecordService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            userInvitation.find({inviter: user._id}).populate('invitee', 'images authenticationStatus').sort('-dateLastModified')
                .exec(function (err, result) {
                    var vCount = 0;
                    var rCount = 0;
                    var users = [];
                    if (result != null) {
                        result.forEach(function (temp) {

                            if (temp.invitee != null) {
                                if (temp.invitee.authenticationStatus) vCount++;
                                users.push(temp.invitee);
                            }
                        });
                        rCount = result.length - vCount;
                        users = users.slice(0, 10);
                    }

                    callback(null, {vCount: vCount, rCount: rCount, totalCount: result.length, users: users})
                });
        }
    })
};

/**
 * 获取我的邀请记录
 * @param token
 * @param page
 * @param callback
 */
exports.getMyInvitationRecordService = function (token, page, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            var index = Number(page) * listPageSize;

            userInvitation.find({inviter: user._id}, '-dateCreated').populate('invitee', 'images nickName community roomUnit showUnit authenticationStatus dateCreated') // 新
            // userInvitation.find({inviter: user._id}, '-dateCreated').populate('invitee', 'images nickName community roomUnit showUnit authenticationStatus') // 旧
                .sort('-dateLastModified').skip(index).limit(listPageSize)
                .exec(function (err, result) {
                    if (result != null) {
                        async.each(result, function (temp, callbackInner) {

                            if (temp.invitee != null) {

                                // 1120-commit-master
                                // 紧急上线-邀请人的时间从用户邀请表的最后更新时间，变成用户表的注册时间
                                if(temp.invitee._doc && temp.invitee._doc.dateCreated) {
                                    temp.dateLastModified = temp.invitee._doc.dateCreated;
                                }

                                temp.invitee._doc.roomUnit = !isNaN(temp.invitee.roomUnit) ? temp.invitee.roomUnit + '单元' : temp.invitee.roomUnit;

                                if (temp.invitee.showUnit != null && !temp.invitee.showUnit) {
                                    temp.invitee.roomUnit = undefined;
                                }
                                temp._doc.status = temp.invitee.authenticationStatus ? 2 : 1;

                                if (temp.invitee.community) {
                                    community.findOne({_id: temp.invitee.community}, 'communityName', function (err, comm) {
                                        temp._doc.communtiyName = comm.communityName;
                                        callbackInner()
                                    })
                                } else {
                                    callbackInner()
                                }
                            } else {
                                callbackInner()
                            }

                        }, function (err) {
                            callback(err, result)
                        })
                    } else {
                        callback(err, []);
                    }
                })
        }
    })
};

/**
 * 我的邀请奖励数量
 * @param token
 * @param callback
 */
exports.getMyInvitationCountService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            userInvitation.find({inviter: user._id, type: 1}, function (err, result) {
                var score = 0;
                var count = 0;
                if (result != null) {
                    result.forEach(function (temp) {
                        score += temp.score;
                    });
                    count = result.length;
                }
                // callback(null, {score: '累计' + score + '积分', count: count})
                callback(null, {score: '', count: 0})
            })
        }
    })
};

exports.getMyInvitationRankService = function (token, vcode, callback) {
    var key = 'rank:invitation:' + moment().startOf('isoWeek').add(-7, 'day').format('YYYYMMDD');
    if (Number(vcode) >= 200000) {
        key = 'rank:invitation:' + moment().startOf('isoWeek').format('YYYYMMDD');
    }
    var data = [];

    logger.info(key);

    redisClient.ZREVRANGE(key, 0, 10, 'WITHSCORES', function (err, result) {
        result.forEach(function (value, i) {
            if (i % 2 == 0) {
                data[i / 2] = {};
                data[i / 2].userId = value;
            } else {
                data[(i - 1) / 2].count = value;
            }
        });

        var list = [];

        async.eachSeries(data, function (temp, callbackInner) {
            Users.findOne({_id: temp.userId}, 'images nickName community').populate('community', 'communityName')
                .exec(function (err, user) {
                    if (user != null) {
                        user._doc.count = temp.count;
                        list.push(user)
                    }
                    callbackInner()
                })
        }, function () {
            callback(null, {rank: list})
        })
    })
};


exports.userSignInService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            var key = 'user:signin:record:' + user._id;
            redisClient.HGETALL(key, function (err, obj) {
                if (obj == null) {
                    /*  宝宝树66小区二次改造    mod   chenf  20170815   start   */
                    /*exports.signInAddScore(user._id, 0, key, null, callback);*/
                    exports.signInAddInfo(user._id, 0, key,token, null, callback);
                    /*  宝宝树66小区二次改造    mod   chenf  20170815   end   */
                } else {
                    if (obj.now === moment().format('YYYYMMDD')) {
                        /*  宝宝树66小区二次改造    add   guo.xiaomin  20170830   start   */
                        // callback(null, {signInMsg: '今日已签到', start: obj.start, now: obj.now}); // 旧
                        var isLuckDraw = obj.isLuckDraw;
                        var url = null;
                        if(!isLuckDraw) {
                            // 兑吧抽奖
                            var opt = {};
                            opt.uid = token;
                            opt.credits = "0";
                            opt.appKey = "41sKUDArdECb7iwntFhewrxywLyb";
                            opt.timestamp = new Date().getTime();
                            opt.redirect = "https://activity.m.duiba.com.cn/newtools/index?id=2345004";
                            opt.appSecret = "2XtFatEJhZGGms8gJLhWoTWikqbR";
                            var arg = ["uid", "credits", "appKey", "timestamp", "redirect", "appSecret"];
                            arg.sort();

                            var str = "";
                            for (var i = 0; i < arg.length; i++) {
                                str += opt[arg[i]];
                            }
                            var sign = md5(str);

                            url = 'http://www.duiba.com.cn/autoLogin/autologin?uid=' + token + '&appKey=' + opt.appKey + '&timestamp='+ opt.timestamp + '&credits=' + opt.credits + '&sign=' + sign + '&redirect='+ opt.redirect;
                            logger.info(url);
                        }
                        callback(null, {signInMsg: '今日已签到', start: obj.start, now: obj.now, isLuckDraw: obj.isLuckDraw, url: url}); // 新
                        /*  宝宝树66小区二次改造    add   guo.xiaomin  20170830   end   */
                    } else {
                        /*  宝宝树66小区二次改造    mod   chenf  20170815   end   */
                        /*exports.signInAddScore(user._id, Number(obj.number), key, obj.start, callback)*/
                        exports.signInAddInfo(user._id, 0, key,token, null,callback);
                        /*  宝宝树66小区二次改造    mod   chenf  20170815   end   */
                   }
                }
            })

        }
    })
};

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170830   start   */
exports.userLuckDrawSuccess = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            var option = {'user': user._id};
            // 与mongodb的ISO日期时间对应
            var today = new Date(moment().format('YYYY-MM-DD'));
            var tomorrow = new Date(moment().add(1, "days").format("YYYY-MM-DD"));
            option.signDate = {$gte: today, $lte: tomorrow};

            signInfo.update(option, {$set : {"isLuckDraw" : true}}).exec(
                function (err, result) {
                    var key = 'user:signin:record:' + user._id;
                    var arg = [key, 'isLuckDraw', true];
                    redisClient.HMSET(arg, function (err, result) {
                        if (err)logger.error(err)
                    });
                    redisClient.EXPIRE(key, 86400);
                    callback(null, '抽奖成功');
                }
            );
        }
    })
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170830   end   */

/*  宝宝树66小区二次改造    add   chenf  20170815   start   */
// 签到抽奖
exports.signInAddInfo = function (userId, number, key, token, start, callback) {
    var now = moment().format('YYYYMMDD');
    start = start ? start : now;
    var arg = [key, 'start', start, 'now', now, 'number', (number + 1) + ''];

    var time = Math.round(moment().startOf("day").add(number >= 6 ? 1 : 2, 'day').toDate() / 1000 - new Date().getTime() / 1000);

    redisClient.HMSET(arg, function (err, result) {
        if (err)logger.error(err)
    });
    redisClient.EXPIRE(key, time);

    //老版本
    redisClient.sadd('app:signin:' + moment().format('YYYYMMDD'), userId);
    redisClient.EXPIRE('app:signin:' + moment().format('YYYYMMDD'), 86400);
    // 签到插入表数据
    var temp = new signInfo();
    temp.user = userId;
    temp.save();

    // 兑吧抽奖
    var opt = {};
    opt.uid = token;
    opt.credits = "0";
    opt.appKey = "41sKUDArdECb7iwntFhewrxywLyb";
    opt.timestamp = new Date().getTime();
    opt.redirect = "https://activity.m.duiba.com.cn/newtools/index?id=2345004";
    opt.appSecret = "2XtFatEJhZGGms8gJLhWoTWikqbR";
    var arg = ["uid", "credits", "appKey", "timestamp", "redirect", "appSecret"];
    arg.sort();

    var str = "";
    for (var i = 0; i < arg.length; i++) {
        str += opt[arg[i]];
    }
    var sign = md5(str);

    var url = 'http://www.duiba.com.cn/autoLogin/autologin?uid=' + token + '&appKey=' + opt.appKey + '&timestamp='+ opt.timestamp + '&credits=' + opt.credits + '&sign=' + sign + '&redirect='+ opt.redirect;
    logger.info(url);
    callback(null, {signInMsg: '签到成功', url: url});
};
/*  宝宝树66小区二次改造    add   chenf  20170815   end   */
exports.signInAddScore = function (userId, number, key, start, callback) {
    var input = {
        userId: userId + '',
        userRole: 1,
        addScore: SIGN_IN_SCORE[number],
        addScoreReason: '签到',
        userActionType: 18
    };

    input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

    scoreProxy.invoke('addScore', [input], function (err, result) {
        if (err) {
            logger.error('Exception happened when addScoreManual ...!' + err.message);
            callback(err)
        } else {
            var data = JSON.parse(decodeURIComponent(result));

            if (data != null && data.status == 0) {

                var now = moment().format('YYYYMMDD');
                start = start ? start : now;
                var arg = [key, 'start', start, 'now', now, 'number', (number + 1) + ''];

                var time = Math.round(moment().startOf("day").add(number >= 6 ? 1 : 2, 'day').toDate() / 1000 - new Date().getTime() / 1000);

                redisClient.HMSET(arg, function (err, result) {
                    if (err)logger.error(err)
                });
                redisClient.EXPIRE(key, time);


                //老版本
                redisClient.sadd('app:signin:' + moment().format('YYYYMMDD'), userId);
                redisClient.EXPIRE('app:signin:' + moment().format('YYYYMMDD'), 86400);

                callback(null, {signInMsg: '签到成功', currentValue: data.data.currentValue, start: start, now: now});
            } else {
                callback({message: '签到失败'})
            }
        }
    });
};

/**
 * 管理员、雷锋团申请
 * @param token
 * @param body
 * @param callback
 */
exports.applyUserRoleService = function (token, body, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            var temp = new UserRoleApply();
            /*  宝宝树66小区五期   mod  小区大使申请 guo.xiaomin  20171121   start   */
            var userTemp = {};
            var realName = body.realName; // 真实姓名
            var wxName = body.wxName; // 微信号
            if(realName) {
                userTemp.realName = realName; // 真实姓名
            }
            if(wxName) {
                userTemp.wxName = wxName; // 微信号
            }
            Users.update({_id: user._id}, userTemp, function(err, updateResult) {
                if (body.name != null) {
                    temp.user = user._id;
                    temp.community = user.community._id;
                    temp.city = user.community.cityId;
                    temp.type = body.type;
                    temp.name = body.name;
                    temp.phone = body.phone;
                    temp.address = body.address;
                    temp.specialty = body.specialty.split(",");
                    temp.save(callback);
                } else {
                    Users.findOne({_id: user._id}, 'nickName', function (err, result) {
                        temp.user = user._id;
                        temp.type = body.type;
                        temp.name = result.nickName;
                        temp.community = user.community._id;
                        temp.city = user.community.cityId;
                        temp.save(callback);
                    });
                }
            });
            /*  宝宝树66小区五期   add  小区大使申请 guo.xiaomin  20171121   end   */
        }
    })
};

/**
 * 管理员、雷锋团查询
 * @param token
 * @param body
 * @param callback
 */
exports.getUserRoleService = function (token, type, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            UserRoleApply.findOne({
                user: token,
                community: user.community._id,
                type: type,
                isValid: true
            }).sort({dateCreated: -1}).limit(1).exec(function (err, result) {
                if (result != null)
                    result._doc.user = user;
                callback(err, result);
            });
        }
    })
};

exports.contactsInviteService = function (input, callback) {
    var array = [];
    input.contacts.forEach(function (item) {
        if (item.phone.indexOf('+86') == 0) {
            item.phone = item.phone.substr(3, item.phone.length);
        }
        item.phone = item.phone.replace(/\s+/g, "");
        array.push(item.phone);
    });

    Users.find({mobilePhone: {$in: array}}, 'mobilePhone images nickName', function (err, result) {
        if (err) return callback(err);

        result.forEach(function (temp) {
            temp._doc.phone = temp.mobilePhone;
        });

        var res = {
            /*宝宝树66小区二次改造    mod   zhangm  20170723   start*/
            message: '我在手机上安装了宝宝树66小区，小区里发生的大事小事邻居们都会发上来，还可以把家里的闲置物品卖给邻居，快下载吧：http://t.cn/R4izR49',
            /*宝宝树66小区二次改造    mod   zhangm  20170723   start*/
        users: result
        };

        callback(null, res);
    })
};

exports.getSplashScreenService = function (callback) {
    splashScreen.find({
        endDate: {$gte: new Date()},
        isValid: true
    }, 'image duration startDate endDate').sort({startDate: 1}).limit(2).exec(callback)
};

exports.getCommunityFounderService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) return callback(err);

        async.series([
            function (callbackInner) {
                /*  宝宝树66小区二次改造    add   小区大使检索添加 chenf  20170817   start   */
                var flag = "";
                // 检索小区大使关联数据
                ambassadorCommunity.find({community: user.community._id, isValid:true}).populate('user')
                    .exec(function (err, result1) {
                    if(result1.length > 0){
                        flag = "1";
                        for (var re in result1) {
                            if (re.user._id == user._id) {
                                // 有创始人，是本小区的
                                flag = "2";
                                var result = re.user;
                                // 检索邀请数据
                                userInvitation.find({inviter: user._id}, 'invitee').populate('invitee', 'community').exec(function (err, count) {
                                    var inviteCount = 0;
                                    if (count != null) {
                                        count.forEach(function (item) {
                                            if(user.community && item.invitee) {
                                                if (user.community._id == item.invitee.community + '') inviteCount++;
                                            }
                                        })
                                    }
                                    result.inviteCount = inviteCount;
                                    // callbackInner(null, {invite: false, user: result})
                                    callbackInner(null, {invite: false, user: result, flag : flag});
                                });

                            }
                        }
                    } else {
                        // 检索该小区的小区大使
                        Users.findOne({community: user.community._id, userRole: 4}, 'nickName images _id huanxinUserName', function (err, result2) {
                            /*  宝宝树66小区二次改造    add   创始人flg添加 luolh  20170725   start   */
                            // if (result == null) return callbackInner(null, {invite: true});
                            // flag :0 无创始人
                            if (result2 == null) return callbackInner(null, {invite: true, flag : "0"});
                            if (result2._id == user._id) {
                                // 有创始人，是本小区的
                                flag = "2";

                                userInvitation.find({inviter: result2._id}, 'invitee').populate('invitee', 'community').exec(function (err, count) {
                                    var inviteCount = 0;
                                    if (count != null) {
                                        count.forEach(function (item) {
                                            if(user.community && item.invitee) {
                                                if (user.community._id == item.invitee.community + '') inviteCount++;
                                            }
                                        })
                                    }
                                    result2._doc.inviteCount = inviteCount;
                                    // callbackInner(null, {invite: false, user: result})
                                    callbackInner(null, {invite: false, user: result2, flag : flag});
                                });

                            } else {
                                // 有创始人，非本小区的
                                flag = "1";
                                callbackInner(null, {invite: false, user: result2, flag : flag});
                            }
                        })
                    }
                });
                // Users.findOne({community: user.community._id, userRole: 4}, 'nickName images _id', function (err, result) {
                //     /*  宝宝树66小区二次改造    add   创始人flg添加 luolh  20170725   start   */
                //     // if (result == null) return callbackInner(null, {invite: true});
                //     // flag :0 无创始人
                //     if (result == null) return callbackInner(null, {invite: true, flag : "0"});
                //     var flag = "";
                //     if (result._id == user._id) {
                //         // 有创始人，是本小区的
                //         flag = "2";
                //     } else {
                //         // 有创始人，非本小区的
                //         flag = "1";
                //     }
                //     /*  宝宝树66小区二次改造    add   创始人flg添加 luolh  20170725   end   */
                //     userInvitation.find({inviter: result._id}, 'invitee').populate('invitee', 'community').exec(function (err, count) {
                //         var inviteCount = 0;
                //         if (count != null) {
                //             count.forEach(function (item) {
                //                 if (user.community._id == item.invitee.community + '') inviteCount++;
                //             })
                //         }
                //         result._doc.inviteCount = inviteCount;
                //         /*  宝宝树66小区二次改造    add   创始人flg添加 luolh  20170725   start   */
                //         // callbackInner(null, {invite: false, user: result})
                //         callbackInner(null, {invite: false, user: result, flag : flag});
                //         /*  宝宝树66小区二次改造    add   创始人flg添加 luolh  20170725   end   */
                //     });
                // })
                /*  宝宝树66小区二次改造    add   小区大使检索添加 chenf  20170817   end   */
            },
            function (callbackInner) {
                UserRoleApply.findOne({
                    user: user._id,
                    community: user.community._id,
                    type: 4,
                    isValid: true
                }).sort({dateCreated: -1}).limit(1).exec(function (err, result) {
                    callbackInner(null, result)
                });
            },
            function (callbackInner) {
                userInvitation.find({inviter: user._id}, 'invitee').populate('invitee', 'community').exec(function (err, result) {
                    var count = 0;
                    if (result != null) {
                        result.forEach(function (item) {
                            if(user.community && item.invitee) {
                                if (user.community._id == item.invitee.community + '') count++;
                            }
                        })
                    }
                    callbackInner(null, count)
                })
            }
        ], function (err, result) {
            result[0].count = result[2];
            if (result[1] != null) {
                result[0].status = result[1].status
            }
            callback(err, result[0]);
        });

    })
};

/* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 mod wangcan 20170927 start */
/**
 * 校验最新用户协议版本
 * @param mobilePhone
 * @param callback
 */
exports.checkProtocolVersionService = function (mobilePhone, callback) {
    var mobilePhone = mobilePhone;
    Users.findOne({
        mobilePhone: mobilePhone
    }, 'id mobilePhone protocolVersion nickName').exec(function (err, result) {
        if (err) {
            callback(err);
        } else {
            if (result == null) {
                // 未注册用户
                callback(null, {status: 0});
            } else {
                if (result.protocolVersion == newProtocolVersion) {
                    // 用户已阅读过最新版本用户协议
                    callback(null, {status: 1});
                } else {
                    // 用户未阅读过最新版本用户协议
                    callback(null, {status: 0});
                }
            }
        }
    });
};
/* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 mod wangcan 20170927 end */
